<template>
	<div class="home_files_view" @click.stop.prevent="">
		<div class="files_title">
           <ul>
               <li :class="{active:show_index==index}" v-for="(item,index) in fileType" @click.stop.prevent="setIndex(index)" :key="'file_'+index">{{item}}</li>
           </ul>
           <span style="cursor:pointer;">
                <img draggable="false" src="static/image/home/close.png" @click.stop.prevent="filesViewClose">
            </span>
        </div>
        <div class="filses_wrap">
            <div class="files_box" v-show="show_index==0">
                <div class="files_head">
                    <div style="display:flex;" class="files_s_w">
                        <div class="search_icon"></div><input type='text' v-model="files_search"><img v-show="files_search.trim()!=''" @click.stop.prevent="files_search=''" src="static/image/home/clear_icon.png">
                    </div>
                </div>
                <div class="files_main" ref="fileScroll">
                    <template v-for="item in files_list">
                        <div class="files_item" :key="'file_'+item.messageId">
                            <div class="f_tiem_m">
                                <div class="f_t_icon">
                                    <img v-lazy="'static/image/home/document.png'">
                                </div>
                                <div class="file_info">
                                    <div class="file_name">{{item.value | interception}}</div>
                                    <div>{{item.duration | convertByte}}&nbsp;|&nbsp;{{item.time | timeFormat}}&nbsp;{{item.sendId==myInfo.id?myInfo.name:item.name}}</div>
                                </div>
                                <div class="files_set">
                                    <Tooltip content="转发" placement="bottom">
                                        <span class="f_sd" @click.stop.prevent='toForwarding(item)'></span>
                                    </Tooltip>
                                    <Tooltip content="下载" placement="bottom" v-if="item.isDownLoad=='0'">
                                        <span class="f_dl" @click.stop.prevent='toDownFile(item)'></span>
                                    </Tooltip>
                                    <Tooltip content="打开" placement="bottom" v-if="item.isDownLoad!='0'&&item.isDownLoad!='loading'">
                                        <span class="f_op"  @click.stop.prevent='toPreviewFile(item)'></span>
                                    </Tooltip>
                                </div>
                            </div>
                            <div class="file_pg">
                                <Progress v-if="item.upload==1" :percent="item.progress?item.progress:0" status="active"></Progress>
                            </div>
                        </div>
                    </template>
                </div>
                <div class="page_wrap" v-show="filesCount.length>pageSize">
                    <Page :total="filesCount.length" show-total :current="files_cur" :page-size='pageSize' @on-change='pageChange'></Page>
                    <div class="goto_w"><div>跳转至</div><input type="number" min="1" v-model="page_num">页&nbsp;<button @click.stop.prevent='goPage'>确定</button></div>
                </div>
            </div>
            <div class="image_box" v-show="show_index==1">
                <viewer :images="img_list" style="height:100%;display: flex;flex-direction: column;">
                    <div ref="imgScroll" class="img_view_box">
                        <template v-for="item in img_list">
                            <div class="img_item images" :key="'img_'+item.messageId">
                                <img viewer='true' v-lazy="$isRelativePath(item.value)">
                                <div class="f_send" @click.stop.prevent='toForwarding(item)'>
                                    <Tooltip content="转发" placement="bottom">
                                        <div class="s_icon_w">
                                            <div class="send_icon"></div>
                                        </div>
                                    </Tooltip>
                                </div>
                            </div>
                        </template>
                    </div>
                    <div class="page_wrap" v-show="imgsCount.length>pageSize">
                        <Page :total="imgsCount.length" show-total :current="imgs_cur" :page-size='pageSize' @on-change='imgPageChange'></Page>
                        <div class="goto_w"><div>跳转至</div><input type="number" min="1" v-model="img_page_num">页&nbsp;<button @click.stop.prevent='imgGoPage'>确定</button></div>
                    </div>
                </viewer>
            </div>
        </div>
	</div>
</template>

<script>
import {mapState} from 'vuex'
	export default {
		name: 'filesView',
		props: {
            toInfo:{
                type:Object,
                default:{
					id: '',
					name: '',
					isGroup: false
                }
            },
            files_show:{
                type:Boolean,
                default:false
            }
		},
		data() {
			return {
                show_index:0,
                fileType:['文件','图片'],
                files_list:[],
                filesCount:[],
                img_list:[],
                files_max:1,
                files_search:'',
                fileCount:60,
                imgCount:60,
                pageSize:20,  //每页显示条数
                files_cur:0, //文件当前页数
                imgs_cur:0,
                page_num:1,
                img_page_num:1,
                imgsCount:[]
			}
        },
        computed:{
            ...mapState(["myInfo","ws"]),
            tableId() {
				return this.myInfo.id
			},
            sqlTable() {
				return {
					userHotKey: `user_hot_key`,
					uninterruptedList: `uninterrupted_list_${this.tableId}`, //免打扰列表
					userInformation: `user_information_${this.tableId}`, //用户信息表
					sessionList: `session_list_${this.tableId}`, //会话列表
					broadcastList: `broadcast_list_${this.tableId}`, //广播列表
					publicList: `public_list_${this.tableId}`, //公众号列表
					groupList: `group_list_${this.tableId}`, //群列表
					messageList: `message_list_${this.tableId}`, //群聊消息表
					privateList: `private_list_${this.tableId}`, //单聊消息表
					publicRecords: `public_records_${this.tableId}`, //公众号记录表
					groupUsers: `group_users_${this.tableId}`, //	groupMessageEnity: 'GroupMessageEnity_' + this.myInfo.id,
					systemTable:`system_${this.tableId}`
				}
			}
        },
        filters: {
            Interception(value) {
				let index = value.lastIndexOf("\/");
				let str = value.substring(index + 1, value.length);
				return str;
			},
            convertByte(byteCount) {
				var count = parseFloat(byteCount),
					unitArr = ['b', 'Kb', 'Mb', 'Gb', 'Tb'],
					index = 0;
				if (!count) return 0;
				for (let i = 0; i < 5; i++) {
					if (count >= 1024) {
						count = count / 1024
						index++
					} else {
						return index > 0 ? count.toFixed(2) + unitArr[index] : count + unitArr[index]
					}
					if (index == 4) {
						return count.toFixed(2) + unitArr[index]
					}
				}
			},
        },
		methods: {
            imgGoPage(){
                this.imgs_cur=parseInt(this.img_page_num);
                this.$forceUpdate();
            },
            goPage(){
                this.files_cur=parseInt(this.page_num);
                this.$forceUpdate();
                console.log(this.page_num,'pagnum');
            },
            imgPageChange(index){
                this.imgs_cur=index;
            },
            pageChange(index){
                this.files_cur=index;
                console.log(index,'页数');
            },
            filesViewClose(){
                this.$emit('filesViewClose');
            },
            fileScrollFn(){
                let a=this.$refs.fileScroll.scrollTop+this.$refs.fileScroll.clientHeight-100;
				let b=this.$refs.fileScroll.scrollHeight;
                console.log(a);
                console.log(b);
				if((b-a)<=200) {
					if (this.fileCount < this.files_list.length){
                        this.fileCount += 30;
                        this.$forceUpdate();
                        console.log(this.fileCount,'count');
					}
				}
            },
            imgScrollFn(){
                let a=this.$refs.imgScroll.scrollTop+this.$refs.imgScroll.clientHeight-100;
				let b=this.$refs.imgScroll.scrollHeight;
				console.log(a);
                console.log(b);
				if((b-a)<=200) {
					if (this.imgCount < this.img_list.length){
                        this.imgCount += 30;
                        this.img_list.push({
                            receiveId:1,
                            sendId: 1,
                            name: 1,
                            value: 1,
                            gender: 1,
                            time: 1,
                            head: "",
                            type: 'text',
                            duration: 1,
                            isDownLoad: 1,
                            messageId: 1,
                            DownLoadId:1
                        })
                        this.img_list.pop();
                        this.$forceUpdate();
                        console.log(this.imgCount,'count');
					}
				}
            },
            toForwarding(temp){
                this.$emit('toForwarding',temp);
            },
            //文件预览
			toPreviewFile(item){
				let _this = this;
				console.log(item,'文件预览');
				let rep=this.$shell("OpenFlieByUrl", [this.$isRelativePath(item.isDownLoad)]);
				rep=JSON.parse(rep);
				console.log(rep,'文件预览');
				if(rep.return_code=="FALSE"){
					this.$Message.info("系统找不到指定的文件,请重新下载");
					this.$set(item,'isDownLoad',0)
					return;
				}
			},
            toDownFile(temp){
                this.$emit('toDownFile',temp);
            },
            //index --->1为搜索,其他不需要参数
			operationalDatabase(statements, index) {
				let to = JSON.stringify({
					Sqlstr: statements
				})
				return arguments[1] ? JSON.parse(this.$shellSQL(to, index)) : JSON.parse(this.$shellSQL(to))
            },
            setIndex(index){
                this.show_index=index;
            },
            searchFile(value){
                this.files_list=[];
                this.files_cur=0;
                let id = this.toInfo.id;
                let isTrue = this.toInfo.isGroup == "1";
                var str;
                if(value){
                    if(isTrue){
                            str =
                    `${isTrue?this.sqlTable.messageList:this.sqlTable.privateList} WHERE value LIKE '%${value}%' AND (receiveId='${id}' OR sendId='${id}')  AND type='file'`;
                    }else{
                            str =
                    `${isTrue?this.sqlTable.messageList:this.sqlTable.privateList} WHERE value LIKE '%${value}%' AND  (receiveId='${id}' OR sendId='${id}')  AND type='file'`;
                    }
                }else{
                    str =
                    `${isTrue?this.sqlTable.messageList:this.sqlTable.privateList} WHERE (receiveId='${id}' OR sendId='${id}') AND type='file'`
                }
                let res = this.operationalDatabase(`SELECT * FROM  ${str} ORDER BY time DESC;`, 1);    //limit 20
                console.log(res,'搜索文件列表');
                // this.fileCount=60;
                this.filesCount=res.list.filter(item => item.isDownLoad!='404');// 新增去除文件发送失败的列，为isDownLoad==404
                console.log(this.filesCount,'去除404的数组====>>>>>>>>>>>>')
                this.files_list = this.filesCount;// 新增会话列表右上角搜索无效的问题
                this.files_cur = 1;
                this.$forceUpdate();
            },
            getImgList(){
                this.img_list=[];
                this.imgs_cur=0;
                let id = this.toInfo.id;
                let isTrue = this.toInfo.isGroup == "1";
                let str;
                if(isTrue){
                    str =
                `${isTrue?this.sqlTable.messageList:this.sqlTable.privateList} WHERE (receiveId='${id}' OR sendId='${id}')  AND type='image'`;
                }else{
                    str =
                `${isTrue?this.sqlTable.messageList:this.sqlTable.privateList} WHERE (receiveId='${id}' OR sendId='${id}')  AND type='image'`;
                }
                let res = this.operationalDatabase(`SELECT * FROM  ${str} ORDER BY time DESC;`, 1);
                this.imgsCount=res.list;
                this.imgs_cur=1;
                console.log(this.imgsCount,'图片');
            }
        },
        created(){
            console.log('文件预览')
            this.searchFile();
            this.getImgList();
        },
        watch:{
            files_search(){
                if(this.files_search.trim()==""){
                    this.searchFile();
                }else{
                    this.searchFile(this.files_search);
                }
            },
            imgs_cur(){
                let starIndex=(this.imgs_cur-1)*this.pageSize;
                let endIndex=this.imgs_cur*this.pageSize;
                this.img_list=this.imgsCount.slice(starIndex,endIndex);
                console.log(starIndex,endIndex,'index',this.imgsCount);
            },
            files_cur(){
                let starIndex=(this.files_cur-1)*this.pageSize;
                let endIndex=this.files_cur*this.pageSize;
                this.files_list=this.filesCount.slice(starIndex,endIndex);
                console.log(starIndex,endIndex,'index',this.files_list);
            },
            page_num(){
                if(this.filesCount.length<=0){
                    this.page_num=1;
                    return;
                }
                let maxcount=Math.ceil(this.filesCount.length/this.pageSize);
                if(this.page_num>=maxcount){
                    this.page_num=parseInt(maxcount);
                }else if(this.page_num<=0){
                    this.page_num=1;
                }else{
                    this.page_num=parseInt(this.page_num);
                }
            },
            img_page_num(){
                 if(this.imgsCount.length<=0){
                    this.img_page_num=1;
                    return;
                }
                let maxcount=this.imgsCount.length/this.pageSize;
                if(this.img_page_num>maxcount){
                    this.img_page_num=parseInt(maxcount);
                }else if(this.img_page_num<=0){
                    this.img_page_num=1;
                }else{
                    this.img_page_num=parseInt(this.img_page_num);
                }
            }
            // filesCount(){
            //     this.files_max=this.filesCount/this.pageSize;
            // }
        }
	}
</script>